package com.likersai.opon.service.impl;

import com.likersai.opon.dao.OponUserMapper;
import com.likersai.opon.pojo.dto.param.OponUserParam;
import com.likersai.opon.pojo.entity.OponUser;
import com.likersai.opon.pojo.vo.req.LoginReq;
import com.likersai.opon.pojo.vo.rsp.LoginRsp;
import com.likersai.opon.service.OponUserService;
import com.likersai.opon.system.exception.OponException;
import com.likersai.opon.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import static com.likersai.opon.constant.ExceptionMsg.NO_USER;


/**
 * User服务类实现类
 *
 * @author sun.ye
 * @since 2020-12-05 16:33
 */
@Service
public class OponUserServiceImpl implements OponUserService {

    OponUserMapper oponUserMapper;

    @Autowired
    public OponUserServiceImpl(OponUserMapper oponUserMapper) {
        this.oponUserMapper = oponUserMapper;
    }


    @Override
    public OponUser queryOponUser(OponUser param) {
        return oponUserMapper.queryOponUser(new OponUserParam());
    }

    @Override
    public LoginRsp login(LoginReq loginInfo) {

        OponUser loginUser = queryOponUser(loginInfo);
        return validLogin(loginInfo,loginUser);
    }

    private OponUser queryOponUser(LoginReq param){
        OponUserParam oponUserParam = new OponUserParam();
        String login = param.getLogin();

        oponUserParam.setLogin(login);
        OponUser oponUser = oponUserMapper.queryOponUser(oponUserParam);
        if (ObjectUtils.isEmpty(oponUser)){
            throw new OponException(NO_USER);
        }
        return oponUser;
    }

    private LoginRsp validLogin(LoginReq loginInfo, OponUser oponUser){

        String pwdBase64 = loginInfo.getPassword();
        String login = loginInfo.getLogin();

        String loginPassword = SecurityUtils.decodeBase64(pwdBase64);
        String loginpasswordSha1 = SecurityUtils.getShaSecurity(loginPassword);
        String userPasswordSha1 = oponUser.getPassword();

        LoginRsp res = new LoginRsp();
        if(loginpasswordSha1.equals(userPasswordSha1)){
            String token = SecurityUtils.getToken(login);
            res.setCheckResult(true);
            res.setToken(token);
        }else {
            res.setCheckResult(false);
        }
        return res;
    }
}